<?php
/**
 * @author: xuzhengyang
 * @Time: 2023/2/20   09:54
 */


namespace app\libraries\exception;

use app\constdir\SysConst;
use Exception;

class ApiException extends Exception
{
    /**
     * @var array 当异常时候返回数据
     */
    protected $with = [];

    /**
     * 记录日期等级
     *
     * @var string
     *
     */
    private string $logLevel = 'LogInfo';

    /**
     * 异常记录日志额外数据
     * @var array
     */
    protected array $logData = [];

    /**
     * ApiException constructor.
     * @param  array  $error
     * @param  array  $args
     * @param  array  $logData
     * @param  string  $level
     */
    public function __construct(array $error, $args = [], array $logData = [], string $level = 'LogInfo')
    {
        if (empty($error) || count($error) != 2) {
            throw new \InvalidArgumentException("异常参数错误");
        }
        list($this->code, $this->message) = $error;
        if (is_array($args) && !empty($args)) {
            $this->message = sprintf($this->message, ...$args);
        } else {
            $this->message = $args ?: $this->message;
        }
        if (in_array($level, SysConst::LOG_LEVEL_LIST)) {
            $this->logLevel = $level;
        }

        $this->logData = $logData;

        parent::__construct($this->message, $this->code);
    }

    public function with(array $data): ApiException
    {
        $this->with = $data;
        return $this;
    }

    public function getData(): array
    {
        return $this->with;
    }

    /**
     * 返回当前异常日志等级
     *
     * @Author YangHB
     * @DateTime 2022-09-13 16:33:36
     *
     * @return string
     */
    public function getLogLevel(): string
    {
        return $this->logLevel;
    }

    /**
     * 获取异常记录日志数据
     * @return array
     */
    public function getLogData(): array
    {
        return $this->logData;
    }
}